<template>
  <div class="filter-wrap">
    <SelectedTagResult :selectedTagList="selectedTagList"
                       @update-sort-tag="updateTagSort"
                       @close-tag="closeTagHandler" />
    <div class="content">
      <SelectedTag :checkableTagList="options"
                   :checkableMap="checkableMap"
                   @check-update="checkTagHandler" />
    </div>
  </div>
</template>

<script>
import SelectedTagResult from './components/SelectedTagResult'
import SelectedTag from './components/SelectedTag'

export default {
  props: {
    options: Array, // 当前多选框的配置
  },
  components: {
    SelectedTagResult,
    SelectedTag,
  },
  data() {
    return {
      selectedTagList: [], // 由checkableMap 转成的 数组 [{name, value, tag}]
      checkableMap: {}, // 当前选中的tags
    }
  },
  methods: {
    // 清空已选
    initSelected() {
      this.selectedTagList = []
      this.checkableMap = {}
      this.$emit('chacked', {})
    },
    closeTagHandler(params) {
      // 删除 tag
      const { fatherTag, key } = params
      this.selectedTagList = this.selectedTagList.filter((item) => {
        this.checkableMap[fatherTag] = {} // 清空，选中
        return item.key !== key
      })
      this.$emit('closeTag', this.checkableMap)
    },
    updateTagSort(value) {
      // 标签被拖动后的最新顺序(更新)
      this.selectedTagList = value
    },
    checkTagHandler(params) {
      // 选中的tag
      const {
        fatherTag,
        childTagItem: { name, value, key },
        checked,
        instance,
      } = params
      // 以父标签为key, 把子标签的item作为值存在对象中
      if (fatherTag in this.checkableMap) {
        if (checked) {
          // 选中
          delete this.checkableMap[fatherTag]
          this.$set(this.checkableMap, fatherTag, {
            name,
            value,
            fatherTag,
            instance,
            key,
          })
        } else {
          this.$set(this.checkableMap, fatherTag, {})
        }
      } else {
        this.$set(this.checkableMap, fatherTag, {
          name,
          value,
          fatherTag,
          instance,
          key,
        })
      }
      this.handleSelectedTagList(this.checkableMap)
      this.$emit('chacked', this.checkableMap)
    },
    handleSelectedTagList(chackedMap) {
      // 处理当前已选参数的list
      const tempList = []
      Object.keys(chackedMap).forEach((key) => {
        const element = chackedMap[key]
        if (!this.$isEmptyObj(element)) {
          // 为空不插入
          tempList.push(element)
        }
      })
      this.selectedTagList = tempList
    },
    // 提供给外部，通过id选中某一个筛选条件
    _toSelectFilterInstanceById(id, fatherTag) {
      if(!this.options) return
      const instance = this.options.find(n => n.name === fatherTag)
      const childTagItem = instance.tagList.find(v => v.value === Number(id))
      const selectedInstance = {
        fatherTag,
        instance,
        childTagItem,
        checked: true
      }
      this.checkTagHandler(selectedInstance)
    },
  },
}
</script>
